<template>
  <div style="position:relative;">
    <loading></loading>
    <error></error>
    <div class="limit g-font-f5">
      <span class="title">{{category ? '前一日' :'昨日'}}</span>
      <span class="content">涨停<b class="number">{{lastData}}</b>只</span>
    </div>

    <div class="g-legend-wrapper">
      <span class="g-legend-title g-font-f5">
        {{currentTime}}
      </span>
      <div class="g-legend-content">
        <span :class="['g-font-f5', 'g-legend-item', average.indexOf('-') == 0 ? 'green' : 'red']">
          平均表现
          <span class="number">{{average}}</span>
        </span>
        <span class="g-font-f5 g-legend-item blue">
          上证指数
          <span class="number">{{shIndex}}</span>
        </span>
      </div>
    </div>
    <div ref="chartLine" class="chart-line">
    </div>
  </div>
</template>

<script>
import echarts from 'echarts/lib/echarts';
import { getTradeTimeArr, max, min, extend } from '@/common/common';
import { pointFormat } from '@/filters/dataTime'

const tradeTime = getTradeTimeArr();

const option = {
  grid: {
    top: '15%',
    bottom: '10%',
    left: '13%',
    right: '13%'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    splitLine: {
      show: true,
      lineStyle: {
        opacity: 0.7,
        type: 'dotted',
        color: '#bac9d8'
      }
    },
    axisTick: {
      show: false
    },      // 隐藏刻度
    axisLine: {
      show: false
    },
    axisLabel: {
      textStyle: {
        fontSize: 10,
        color: '#a5a5a5'
      }
    },   // x轴 文字样式
    axisPointer: {
      show: true,
      type: 'line',
      lineStyle: {
        type: 'solid'
      },
      label: {
        show: false,
        backgroundColor: 'transparent',
        textStyle: {
          color: 'transparent'
        }
      }
    }
  },
  yAxis: [{
    name: '涨跌幅',
    nameTextStyle: {
      color: '#555'
    },
    splitLine: {
      lineStyle: {
        opacity: 0.7,
        type: 'dotted',
        color: '#bac9d8'
      }
    },
    axisTick: {
      show: false
    },      // 隐藏刻度
    axisLine: {
      show: false
    },
    axisLabel: {
      textStyle: {
        fontSize: 10,
        color: '#a5a5a5'
      }
    }    // 轴 文字样式
  }, {
    name: '上证指数',
    nameTextStyle: {
      color: '#555'
    },
    axisTick: {
      show: false
    },    // 隐藏刻度
    splitLine: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      textStyle: {
        fontSize: 10,
        color: '#a5a5a5'
      }
    }   // 轴 文字样式
  }],
  series: [
    {
      name: '上证指数',
      yAxisIndex: 1,
      type: 'line',
      itemStyle: {
        normal: {
          color: '#6c9bd2'
        }
      },
      lineStyle: {
        normal: {
          width: 1,
          color: '#6c9bd2',
          type: 'dotted'
        }
      },
      smooth: true,
      symbol: 'none'
    },
    {
      type: 'line',
      smooth: true,
      showSymbol: false,
      sampling: 'average',
      data: []
    }
  ]
};

export default {
  name: 'tommorow-chart',
  data () {
    return {
      lastData: 0,
      // currentTime: '--',
      selectIndex: 0,
      index: 0,
      shIndex: '',
      average: '',
      currentTime: '',
      menuTabBar: [
        {name: '1个交易日'},
        {name: '5个交易日'}
      ]
    }
  },
  props: {
    chartData: {
      type: Object
    },
    category: {
      type: Number
    }
  },
  methods: {
    legendInit() {
      const time = this.chartData.average.slice(-1)[0][0];
      this.currentTime = this.category ? time : time.slice(0, 5);
      const hqIndex = this.chartData.indexData.length == 0 ? ''
        : this.category ? this.chartData.indexData.slice(-1)[0]
        : this.chartData.indexData[tradeTime.indexOf(time)] || '';

      Object.assign(this.$data, {
        shIndex: hqIndex,
        average: this.chartData.average.slice(-1)[0][1]
          ? (this.category
            ? (this.chartData.average.slice(-1)[0][1] * 100).toFixed(2) + '%'
            : (this.chartData.average.slice(-1)[0][1] / 100).toFixed(2) + '%')
          : ''
      });
    },
    chartSelected(params) {
      this.currentTime = this.category ? params[0].axisValue : params[0].axisValue.slice(0, 5);

      const params0 = params.find(item => item.seriesIndex == 0)
      const params1 = params.find(item => item.seriesIndex == 1)
      Object.assign(this.$data, {
        shIndex: params0 ? this.chartData.indexData[params0.dataIndex] : '',
        average: params1
          ? (this.category
            ? (params1.value[1] * 100).toFixed(2) + '%'
            : (params1.value[1] / 100).toFixed(2) + '%')
          : ''
      });
    },
    renderChart () {
      this.chartData.xtime = this.category ? this.chartData.xtime.map(item => pointFormat(item)) : tradeTime
      const axisLabel = this.category ? { interval: null } : { interval: 59 };
      const splitLine = this.category ? { interval: null } : { interval: 59 };

      this.lastData = this.chartData.lastData;

      const getMedian = (arr) => (max(arr) + min(arr)) / 2;
      const indexMedian = getMedian(this.chartData.indexData);
      const maxIndex = max(this.chartData.indexData) - indexMedian;
      const minIndex = min(this.chartData.indexData) - indexMedian;
      const indexInterval = max([Math.abs(maxIndex), Math.abs(minIndex)]) * 1.2;

      const maxAver = max(this.chartData.average.map(item => item[1]));
      const minAver = min(this.chartData.average.map(item => item[1]));
      let INTERVAL = max([Math.abs(maxAver), Math.abs(minAver)]);
      INTERVAL = INTERVAL || 1;

      const ratio = maxAver <= 0 ? 0
          : minAver >= 0 ? 1
          : maxAver + Math.abs(minAver) == 0 ? 1
          : maxAver / (maxAver + Math.abs(minAver));

      this.chartLine.clear();
      this.chartLine.setOption(extend(option, {
        yAxis: [{
          axisLabel: {
            formatter: (v) => {
              return this.category ? `${(v * 100).toFixed(2)}%` : `${(v / 100).toFixed(2)}%`
            }
          },
          max: INTERVAL * 1.2,
          min: -INTERVAL * 1.2,
          interval: INTERVAL * 0.6
        }, {
          min: minIndex * 1.2,
          max: maxIndex * 1.2,
          interval: indexInterval / 2,
          axisLabel: {
            formatter: (v) => {
              return (v + indexMedian).toFixed(0)
            }
          }
        }],
        xAxis: {
          data: this.chartData.xtime,
          axisLabel,
          splitLine
        },
        series: [{
          data: this.chartData.indexData.map((v) => v - indexMedian)
        }, {
          data: this.chartData.average,
          lineStyle: {
            normal: {
              width: 1,
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#eb333b'
                }, {
                  offset: ratio, color: '#eb333b'
                }, {
                  offset: ratio, color: '#1aae52'
                }, {
                  offset: 1, color: '#1aae52'
                }],
                globalCoord: false // 缺省为 false
              }
            }
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(226, 70, 70, 0.2)'
                }, {
                  offset: ratio, color: 'rgba(226, 70, 70, 0.2)'
                }, {
                  offset: ratio, color: 'rgba(26, 174, 82, 0.2)'
                }, {
                  offset: 1, color: 'rgba(26, 174, 82, 0.2)'
                }],
                globalCoord: false
              }
            }
          },
          symbol: `image://${require(`@/assets/images/orangeSymbol.svg`)}`
        }],
        tooltip: {
          formatter: this.chartSelected
        }
      }))

      setTimeout(() => {
        this.$store.dispatch('hideLoading')                // 图表渲染成功    loading消失
        this.legendInit();
      }, 0)
    }
  },
  watch: {
    chartData: function (val, oldVal) {
      this.index = val.average.length > 241 ? 240 : val.average.length - 1;
      this.renderChart();
    }
  },
  mounted () {
    this.$store.dispatch('showLoading');
    this.chartLine = echarts.init(this.$refs.chartLine);
    // this.chartLine.setOption(option);
  },
  beforeDestroy () {
    echarts.dispose(this.chartLine);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  @import '../../../assets/css/common.less';
  .limit{
    border-bottom: 1px #ddd solid;
    margin: 0 .15rem .07rem;
    padding-bottom: .07rem;
    text-align: left;
    overflow: hidden;
    .content{
      padding-left: .36rem;
      .number{
        font-weight: normal;
        padding-left: .05rem;
      }
    }
  }
  .chart-line {
  height: 2.43rem;
  padding: .1rem 0;
  }
  .g-legend-title {
    width: 0.5rem;
    padding-top: 0.01rem;
  }
  .g-legend-content {
    margin-left: 0.33rem;
    .g-legend-item {
      width: 50%;
    }
  }
</style>
